#pragma once
#include <iostream>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
using  namespace std;
#include <arpa/inet.h>
#include <strings.h>
#include <netinet/in.h>
#include <unistd.h>
#include "Inetaddr.hpp"
#include <functional>

const static int defaultfd = -1;
using func_t = function<string(const string&,bool& ok)>;


class udpserver
{
public:
    udpserver(uint16_t port,func_t func)
    :_sockfd(defaultfd),_port(port),_isrunning(false),_func(func)
    {}
 
    void InitServer()
    {
        //1创建udp socket套接字 必须要做的
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd < 0)
        {
            cout << "创建socket套接字失败" << endl;
            exit(1);
        }
        cout << "创建socket成功 sockfd:" << _sockfd << endl;

        //2.0 填充sockeaddr_in结构

        //struct sockaddr_in local;
        sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);//port要经过网路传输给对面，先到网路，_port:主机序列，转成网路序列
        //字符串风格的点分十进制的ip地址转成4字节ip
        //主机序列，转成网路序列
        //local.sin_addr.s_addr = inet_addr(_ip.c_str());//"192.168.3.1" -> 字符串风格的点分十进制的ip地址-> 4字节ip
        local.sin_addr.s_addr = INADDR_ANY;
        //2.1 bind sockfd和网路信息（ip + Port）
        int n = bind(_sockfd,(sockaddr*)&local,sizeof(local));

        if(n < 0)
        {
            cout << "bind失败" << endl;
            exit(2);
        }
        cout << "bind成功" << endl;
    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            char buffer[1024];

            sockaddr_in peer;
            socklen_t len = sizeof(peer);

            ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(sockaddr*)&peer,&len);
            
            if(n > 0)
            {
                buffer[n] = 0;
                InetAddr addr(peer);
                cout << "收到来自[" << addr.ip().c_str() << " " << addr.port() << "]的消息：" << buffer << endl;
                bool ok;
                string response = _func(buffer,ok);
                (void)ok;
                sendto(_sockfd,response.c_str(),response.size(),0,(sockaddr*)&peer,len);
            }

            // sleep(1);
            // cout << "服务器正在运行" << endl;
        }
        _isrunning = false;
    }

    ~udpserver()
    {

    }

private:
    int _sockfd;
    //string _ip;
    uint16_t _port;//服务器所用的端口号
    bool _isrunning;
    func_t _func;
};





